<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .test-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border-color: #bee5eb;
            color: #0c5460;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 3px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>API连接测试</h1>
        
        <div class="test-section">
            <h3>1. 基础连接测试</h3>
            <button onclick="testConnection()">测试服务器连接</button>
            <div id="connectionResult"></div>
        </div>
        
        <div class="test-section">
            <h3>2. API端点测试</h3>
            <button onclick="testGetUser()">测试获取用户 (GET)</button>
            <button onclick="testCreateUser()">测试创建用户 (POST)</button>
            <div id="apiResult"></div>
        </div>
        
        <div class="test-section">
            <h3>3. CORS测试</h3>
            <button onclick="testCORS()">测试跨域请求</button>
            <div id="corsResult"></div>
        </div>
        
        <div class="test-section">
            <h3>4. 完整表单测试</h3>
            <form id="testForm">
                <div style="margin-bottom: 10px;">
                    <label>用户名: <input type="text" name="username" value="testuser123" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>真实姓名: <input type="text" name="realName" value="测试用户" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>用户类型: 
                        <select name="userType" required>
                            <option value="student">学生</option>
                            <option value="teacher">教师</option>
                            <option value="staff">职工</option>
                        </select>
                    </label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>学号/工号: <input type="text" name="studentId" value="TEST001" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>班级/部门: <input type="text" name="classDepartment" value="测试班级" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>手机号: <input type="tel" name="phone" value="13800000001" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>邮箱: <input type="email" name="email" value="test@test.com" required></label>
                </div>
                <div style="margin-bottom: 10px;">
                    <label>密码: <input type="password" name="password" value="123456" required></label>
                </div>
                <button type="submit">提交表单</button>
            </form>
            <div id="formResult"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script>
    <script>
        const API_BASE_URL = '/api';
        
        function showResult(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            element.innerHTML = `<div class="${type}"><pre>${message}</pre></div>`;
        }
        
        async function testConnection() {
            try {
                showResult('connectionResult', '正在测试连接...', 'info');
                const response = await fetch('http://localhost:8081/api/users/1');
                if (response.ok) {
                    const data = await response.json();
                    showResult('connectionResult', `✅ 连接成功！\n状态码: ${response.status}\n响应: ${JSON.stringify(data, null, 2)}`, 'success');
                } else {
                    showResult('connectionResult', `⚠️ 连接成功但API返回错误\n状态码: ${response.status}\n响应: ${await response.text()}`, 'error');
                }
            } catch (error) {
                showResult('connectionResult', `❌ 连接失败: ${error.message}`, 'error');
            }
        }
        
        async function testGetUser() {
            try {
                showResult('apiResult', '正在测试GET请求...', 'info');
                const response = await axios.get(`${API_BASE_URL}/users/1`);
                showResult('apiResult', `✅ GET请求成功！\n${JSON.stringify(response.data, null, 2)}`, 'success');
            } catch (error) {
                showResult('apiResult', `❌ GET请求失败: ${error.message}\n${error.response ? JSON.stringify(error.response.data, null, 2) : ''}`, 'error');
            }
        }
        
        async function testCreateUser() {
            try {
                showResult('apiResult', '正在测试POST请求...', 'info');
                const userData = {
                    username: 'testapi' + Date.now(),
                    realName: '测试API用户',
                    userType: 'student',
                    studentId: 'API' + Date.now(),
                    classDepartment: 'API测试班级',
                    phone: '13800000002',
                    email: 'testapi@test.com',
                    password: '123456'
                };
                
                const response = await axios.post(`${API_BASE_URL}/users`, userData);
                showResult('apiResult', `✅ POST请求成功！\n${JSON.stringify(response.data, null, 2)}`, 'success');
            } catch (error) {
                showResult('apiResult', `❌ POST请求失败: ${error.message}\n状态码: ${error.response?.status}\n响应: ${error.response ? JSON.stringify(error.response.data, null, 2) : ''}`, 'error');
            }
        }
        
        async function testCORS() {
            try {
                showResult('corsResult', '正在测试CORS...', 'info');
                const response = await fetch(`${API_BASE_URL}/users/1`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Origin': window.location.origin
                    }
                });
                
                const corsHeaders = {
                    'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
                    'Access-Control-Allow-Methods': response.headers.get('Access-Control-Allow-Methods'),
                    'Access-Control-Allow-Headers': response.headers.get('Access-Control-Allow-Headers')
                };
                
                showResult('corsResult', `✅ CORS测试完成！\nCORS头信息: ${JSON.stringify(corsHeaders, null, 2)}`, 'success');
            } catch (error) {
                showResult('corsResult', `❌ CORS测试失败: ${error.message}`, 'error');
            }
        }
        
        document.getElementById('testForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            try {
                showResult('formResult', '正在提交表单...', 'info');
                const formData = new FormData(e.target);
                const userData = Object.fromEntries(formData.entries());
                
                // 添加时间戳避免重复
                userData.username += Date.now();
                userData.studentId += Date.now();
                userData.email = `test${Date.now()}@test.com`;
                
                console.log('提交的数据:', userData);
                
                const response = await axios.post(`${API_BASE_URL}/users`, userData, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                showResult('formResult', `✅ 表单提交成功！\n${JSON.stringify(response.data, null, 2)}`, 'success');
            } catch (error) {
                console.error('表单提交错误:', error);
                showResult('formResult', `❌ 表单提交失败: ${error.message}\n状态码: ${error.response?.status}\n详细错误: ${error.response ? JSON.stringify(error.response.data, null, 2) : ''}`, 'error');
            }
        });
        
        // 页面加载时自动测试连接
        window.addEventListener('load', () => {
            setTimeout(testConnection, 1000);
        });
    </script>
</body>
</html> 